<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>交叉存放顶点数据</title>

    <!-- 顶点着色器 -->
    <script id="shader-vs" type="x-shader/x-vertex">
        attribute vec3 aVertexPosition;
        attribute vec4 aVertexColor;
        varying vec4 vColor;

        void main() {
            vColor = aVertexColor;
            gl_Position = vec4(aVertexPosition, 1.0);
        }
    </script>

    <!-- 片段着色器 -->
    <script id="shader-fs" type="x-shader/x-fragment">
        precision mediump float;
  
        varying vec4 vColor;
        void main() {
            gl_FragColor = vColor;
        }
    </script>

    <script>
        var gl;
        var canvas;
        var shaderProgram;
        var vertexBuffer;

        function createGLContext(canvas) {
            var names = ["webgl", "experimental-webgl"];
            var context = null;
            for (var i = 0; i < names.length; i++) {
                try {
                    context = canvas.getContext(names[i]);
                } catch (e) { }
                if (context) {
                    break;
                }
            }
            if (context) {
                // 添加动态属性记录画布的大小
                context.viewportWidth = canvas.width;
                context.viewportHeight = canvas.height;
            } else {
                alert("Failed to create WebGL context!");
            }
            return context;
        }

        function setupShaders() {
            // 从 DOM 上创建对应的着色器
            vertexShader = loadShaderFromDOM("shader-vs");
            fragmentShader = loadShaderFromDOM("shader-fs");

            // 创建程序并连接着色器
            shaderProgram = gl.createProgram();
            gl.attachShader(shaderProgram, vertexShader);
            gl.attachShader(shaderProgram, fragmentShader);
            gl.linkProgram(shaderProgram);

            // 连接失败的检测
            if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
                alert("Failed to setup shaders");
            }

            // 使用着色器
            gl.useProgram(shaderProgram);

            // 创建动态属性获取着色器中 aVertexPosition 属性的位置
            shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            // 创建动态属性获取着色器中 aVertexColor 属性的位置
            shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");

            // 设定两个属性为数组类型的变量数据
            gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
            gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
        }

        function loadShaderFromDOM(id) {
            // 获取 DOM
            var shaderScript = document.getElementById(id);

            if (!shaderScript) {
                return null;
            }

            // 获取着色器代码
            var shaderSource = "";
            var currentChild = shaderScript.firstChild;
            while (currentChild) {
                if (currentChild.nodeType == 3) { // 3 corresponds to TEXT_NODE
                    shaderSource += currentChild.textContent;
                }
                currentChild = currentChild.nextSibling;
            }

            // 创建着色器
            var shader;
            if (shaderScript.type == "x-shader/x-fragment") {
                shader = gl.createShader(gl.FRAGMENT_SHADER);
            } else if (shaderScript.type == "x-shader/x-vertex") {
                shader = gl.createShader(gl.VERTEX_SHADER);
            } else {
                return null;
            }

            // 编译着色器
            gl.shaderSource(shader, shaderSource);
            gl.compileShader(shader);

            // 判断编译是否成功
            if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
                alert(gl.getShaderInfoLog(shader));
                return null;
            }
            return shader;
        }

        function setupBuffers() {
            // 创建顶点缓冲
            vertexBuffer = gl.createBuffer();
            // 绑定顶点缓冲
            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
            // 定义顶点数据
            var triangleVertices = [
                //( x     y     z )  (r     g    b    a )
                // --------------------------------------
                0.0, 0.5, 0.0, 255, 0, 0, 255, // V0
                0.5, -0.5, 0.0, 0, 250, 6, 255, // V1
                -0.5, -0.5, 0.0, 0, 0, 255, 255  // V2
            ];

            var nbrOfVertices = 3;

            // 计算出一个顶点数据占用的字节数
            var vertexSizeInBytes = 3 * Float32Array.BYTES_PER_ELEMENT + 4 * Uint8Array.BYTES_PER_ELEMENT;
            // 计算出一个顶点数据占用的4个字节数
            var vertexSizeInFloats = vertexSizeInBytes / Float32Array.BYTES_PER_ELEMENT;

            // 创建二进制字节流和操作视图
            var buffer = new ArrayBuffer(nbrOfVertices * vertexSizeInBytes);
            var positionView = new Float32Array(buffer);
            var colorView = new Uint8Array(buffer);
            // 将数据写入字节流中
            var positionOffsetInFloats = 0;
            var colorOffsetInBytes = 12;
            var k = 0;
            for (var i = 0; i < nbrOfVertices; i++) {
                positionView[positionOffsetInFloats] = triangleVertices[k];         // x
                positionView[1 + positionOffsetInFloats] = triangleVertices[k + 1]; // y
                positionView[2 + positionOffsetInFloats] = triangleVertices[k + 2]; // z
                colorView[colorOffsetInBytes] = triangleVertices[k + 3];            // R
                colorView[1 + colorOffsetInBytes] = triangleVertices[k + 4];        // G
                colorView[2 + colorOffsetInBytes] = triangleVertices[k + 5];        // B
                colorView[3 + colorOffsetInBytes] = triangleVertices[k + 6];        // A
                positionOffsetInFloats += vertexSizeInFloats;
                colorOffsetInBytes += vertexSizeInBytes;
                k += 7;
            }

            // 提交顶点数据
            gl.bufferData(gl.ARRAY_BUFFER, buffer, gl.STATIC_DRAW);
            vertexBuffer.positionSize = 3;
            vertexBuffer.colorSize = 4;
            vertexBuffer.numberOfItems = 3;
        }

        function draw() {
            // 设置视口大小, 使用像素, 调整该大小不影响显示内容，只影响图像在 Canvas 上显示的位置和尺寸
            gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
            // 清除颜色缓冲
            gl.clear(gl.COLOR_BUFFER_BIT);
            // 将提交的顶点数据绑定到着色器的 aVertexPosition 属性
            gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexBuffer.positionSize, gl.FLOAT, false, 16, 0);
            // 将提交的顶点数据绑定到着色器的 aVertexColor 属性
            gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexBuffer.colorSize, gl.UNSIGNED_BYTE, true, 16, 12);
            // 绘制图像
            gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numberOfItems);
        }

        function startup() {
            canvas = document.getElementById("myGLCanvas");
            gl = createGLContext(canvas);
            setupShaders();
            setupBuffers();
            gl.clearColor(1, 1, 1, 1);
            draw();
        }
    </script>
</head>

<body onload="startup();">
    <canvas id="myGLCanvas" width="500" height="500"></canvas>
</body>

</html>